package com.yunkaweilai.android.activity.lanya;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.bilibili.boxing.model.entity.impl.ImageMedia;
import com.bilibili.boxing.utils.ImageCompressor;
import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.login.IndustryActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.ImageUploadModel;
import com.yunkaweilai.android.model.StoreInfoModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.PicturePickerHelper;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/5/2.
 */

public class UpdateStoreInfoActivity extends BaseActivity {

    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.id_img_logo)
    ImageView idImgLogo;
    @BindView(R.id.id_edt_name)
    EditText idEdtName;
    @BindView(R.id.id_tv_type)
    TextView idTvType;
    @BindView(R.id.id_llayout_type)
    LinearLayout idLlayoutType;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    private Gson gson = new Gson();
    private StoreInfoModel storeInfoModel;
    private String mPicPath = "";

    private String store_logo = "";
    private String industry_code = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_store);
        ButterKnife.bind(this);
        new TitleBuilder(this).setTitleText("修改店铺资料").setLeftImage(R.mipmap.ic_go_back)
                .setRightText("保存")
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                }).setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initSave();
            }
        });
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        initHttp();
        initClick();
        dismissProgressDialog();
    }


    private void initSave() {
        showProgressDialog("正在保存资料");
        if (store_logo == null) {//不加会出bug
            store_logo = "1";
        }
        HttpRequest.postUrl(Api.SAVE_STORE_INFO)
                .addParams("store_logo", store_logo)
                .addParams("sub_store_name", idEdtName.getText().toString() + "")
                .addParams("industry_code", industry_code)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            setResult(RESULT_OK, new Intent(mAc, StoreInfoActivity.class));
                            showToast("保存成功");
                            finish();
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });

    }

    private void initClick() {
        idImgLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String cachePath = BoxingFileHelper.getCacheDir(mAc);
//                if (TextUtils.isEmpty(cachePath)) {
//                    showToast(R.string.storage_deny);
//                    return;
//                }
//                Uri destUri = new Uri.Builder()
//                        .scheme("file")
//                        .appendPath(cachePath)
//                        .appendPath(String.format(Locale.US, "%s.jpg", System.currentTimeMillis()))
//                        .build();
//                BoxingConfig singleCropImgConfig = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).withCropOption(new BoxingCropOption(destUri).aspectRatio(12, 4)).needCamera();
//                Boxing.of(singleCropImgConfig).withIntent(mAc, PhotoPickerActivity.class).start(mAc, 123);
                PicturePickerHelper.pickLogo(UpdateStoreInfoActivity.this);
            }
        });

        idLlayoutType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(mAc, IndustryActivity.class), 456);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 123) {
                final ArrayList<BaseMedia> medias = Boxing.getResult(data);
                BaseMedia baseMedia = medias.get(0);
                if (!(baseMedia instanceof ImageMedia)) {
                    return;
                }
                showProgressDialog("请稍等，图片上传中...");
                final ImageMedia imageMedia = (ImageMedia) baseMedia;
                //对返回的图片进行压缩
                if (imageMedia.compress(new ImageCompressor(this))) {
                    imageMedia.removeExif();
                }
                //这个不进行压缩，店铺图片大点就大点吧
                mPicPath = imageMedia.getPath();
                uploadFile(mPicPath);
            } else if (requestCode == 456) {
                String stringExtra = data.getStringExtra(IndustryActivity.INDUSTRY_NAME);
                idTvType.setText(stringExtra);
                industry_code = data.getStringExtra(IndustryActivity.INDUSTRY_CODE);
            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                String uri = PicturePickerHelper.onPickLogoOrAvatarActivityResult(requestCode, resultCode, data);
                if (!StringUtils.isEmpty(uri)) {
                    uploadFile(uri);
                } else {
                    showToast("未选择照片");
                }
            }
        }
    }


    //文件上传
    private void uploadFile(final String mPicPath) {
        Map<String, String> paprms = new HashMap<>();
        paprms.put("token", BaseApplication.getToken());
        OkHttpUtils.post().addFile("file", "shop.jpg", new File(mPicPath))
                .url(Api.IMAGE_UPLOAD).params(paprms).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        showToast("上传失败");
                    }
                });
            }

            @Override
            public void onResponse(final String response, int id) {
                boolean isChecked = Utils.checkCode(mAc, response);
                final Gson gson = new Gson();
                if (!isChecked) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            GlideUtils.loadImage(mAc, new File(mPicPath), idImgLogo);
                            dismissProgressDialog();
                            ImageUploadModel imageUploadModel = gson.fromJson(response, ImageUploadModel.class);
                            store_logo = imageUploadModel.getData().getPath();
                            PictureFileUtils.deleteCacheDirFile(UpdateStoreInfoActivity.this);
                        }
                    });
                }
            }
        });
    }

    private void initHttp() {
        HttpRequest.postUrl(Api.STORE_INFO)
                .execute(new PostProcess.StringCallBack() {

                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            storeInfoModel = gson.fromJson(json, StoreInfoModel.class);
                            initView();
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }

                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
    }

    private void initView() {
        if (idMultipleStatusView != null) {
            idMultipleStatusView.showContent();
        }
        StoreInfoModel.DataBean.InfoBean info = storeInfoModel.getData().getInfo();
        store_logo = info.getStore_logo();
        industry_code = info.getIndustry_code();
        GlideUtils.loadNoPlaceImage(mAc, info.getStore_logo(), idImgLogo);
        idEdtName.setText(info.getStore_name() + "");
        idTvType.setText(info.getIndustry_name() + "");

    }

}
